package com.sphd.Restaurant.fragments.homefragments;

import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.amap.api.maps.AMapUtils;
import com.amap.api.maps.model.LatLng;
import com.android.volley.VolleyError;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.sphd.Restaurant.R;
import com.sphd.Restaurant.activity.RestaurantPageActivity;
import com.sphd.Restaurant.base.LazyLoadFragment;
import com.sphd.Restaurant.infos.RestaurantInfo;
import com.sphd.Restaurant.model.Model;
import com.sphd.Restaurant.presenter.AllRestP;
import com.sphd.Restaurant.utils.Constants;
import com.sphd.Restaurant.utils.MyUtils;
import com.sphd.Restaurant.utils.VolleyErrorHelper;
import com.sphd.Restaurant.views.AllView;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * Created by Hu on 2016/9/27.
 */

public class AllRestaurantFragment extends LazyLoadFragment implements AllView {


    @BindView(R.id.my_recy)
    RecyclerView myRecy;
    @BindView(R.id.my_srf)
    SwipeRefreshLayout mySrf;
    BaseQuickAdapter<RestaurantInfo> baseQuickAdapter;
    List<RestaurantInfo> infos;
    private int ipage = 1;//加载数据时的页数
    AllRestP allRestP;

    @Override
    public int getLayout() {
        return R.layout.recy_and_swf;
    }

    @Override
    public void initViews(View view) {
        ButterKnife.bind(this, view);
        infos = new ArrayList<>();
        setRefresh(mySrf);
        setRecy(myRecy);
        baseQuickAdapter = new BaseQuickAdapter<RestaurantInfo>(R.layout.item_rest, infos) {
            @Override
            protected void convert(BaseViewHolder helper, RestaurantInfo item) {
                ImageView imageView = helper.getView(R.id.iv_restaurant_img);
                setImage(imageView, item.getCg_pic());
                helper.setText(R.id.tv_restaurantname, item.getCg_name())
                        .setText(R.id.tv_openTime, "营业时间:" + item.getCg_openst() + "~" + item.getCg_openet());
                if (item.isCg_isosale()) {
                    helper.setText(R.id.tv_DeliverMealsTime, "送餐时间:" + item.getCg_sendst() + "~" + item.getCg_sendet());
                }
                TextView tvIsDeliverMeals = helper.getView(R.id.tv_isDeliverMeals);
                TextView tvIsCoupon = helper.getView(R.id.tv_isCoupon);
                TextView tvIsRecharge = helper.getView(R.id.tv_isRecharge);
                if (item.isCg_isosale()) {
                    tvIsDeliverMeals.setVisibility(View.GONE);
                } else {
                    tvIsDeliverMeals.setVisibility(View.GONE);
                }
                if (item.isCg_isyh()) {
                    tvIsCoupon.setVisibility(View.VISIBLE);
                } else {
                    tvIsCoupon.setVisibility(View.GONE);
                }
                if (item.isCg_iscz()) {
                    tvIsRecharge.setVisibility(View.VISIBLE);
                } else {
                    tvIsRecharge.setVisibility(View.GONE);
                }
                if (!TextUtils.isEmpty(getString(Constants.LOT)) && !TextUtils.isEmpty(getString(Constants.LAT))) {

                    float myDistance = AMapUtils.calculateLineDistance(new LatLng(Double.parseDouble(getString(Constants.LAT)),Double.parseDouble(getString(Constants.LOT))),
                            new LatLng(item.getCg_lat(),item.getCg_lng()));


                    if (myDistance / 1000 >= 1) {
                        helper.setText(R.id.my_distance, turn(myDistance / 1000, 1) + "km");
                    } else {
                        helper.setText(R.id.my_distance, turn(myDistance, 0) + "m");
                    }
                }

            }
        };
        baseQuickAdapter.openLoadAnimation();
        baseQuickAdapter.openLoadMore(10);
        myRecy.setAdapter(baseQuickAdapter);
        initEvent();
    }

    private void initEvent() {
        baseQuickAdapter.setOnLoadMoreListener(() -> {
            ipage++;
            addDate();
        });
        mySrf.setOnRefreshListener(() -> {
            infos.clear();
            ipage = 1;
            baseQuickAdapter.openLoadMore(10);
            baseQuickAdapter.removeAllFooterView();
            addDate();
        });
        /*点击事件*/
        myRecy.addOnItemTouchListener(new OnItemClickListener() {
            @Override
            public void SimpleOnItemClick(BaseQuickAdapter adapter, View view, int position) {
                Bundle bundle =new Bundle();
                bundle.putString(Constants.TAG,context.getClass().getName());
                bundle.putSerializable(Constants.RESTAURANT,infos.get(position));
                startActivity(RestaurantPageActivity.class,bundle);


            }
        });

    }

    public void setChooseRefresh() {
        if (isLoadDataCompleted()) {
            infos.clear();
            ipage = 1;
            baseQuickAdapter.openLoadMore(10);
            baseQuickAdapter.removeAllFooterView();
            addDate();
        }
    }

    @Override
    public void loadData() {
        allRestP = new AllRestP(this);
        addDate();
    }

    private void addDate() {
        if (MyUtils.isNetworkAvailable(context)) {
            String city = null;
            try {
                if (TextUtils.isEmpty(getString(Constants.CTY))) {
                    if (!TextUtils.isEmpty(getString(Constants.LASTCITY))) {
                        city = getString(Constants.LASTCITY);
                    }else {
                        city="北京";
                    }
                } else {
                    city = getString(Constants.CTY);
                }
                String urlHome = null;
                if (!TextUtils.isEmpty(getString(Constants.LOT)) && !TextUtils.isEmpty(getString(Constants.LAT))) {
                    urlHome = Model.HTTPURL + Model.ALLRESTAURANT + "curpage=" + ipage + "&pageno=10&city="
                            + URLEncoder.encode(city, "UTF-8") + "&lat=" + getString(Constants.LAT) + "&lng=" + getString(Constants.LOT);
                } else {
                    urlHome = Model.HTTPURL + Model.ALLRESTAURANT + "curpage=" + ipage + "&pageno=10&city="
                            + URLEncoder.encode(city, "UTF-8");
                }
                allRestP.addData(urlHome);
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        } else {
            toast("当前网络不可用，请检查网络设置。");
            mySrf.setRefreshing(false);
        }

    }

    @Override
    public void refreshList(List<RestaurantInfo> getmsg) {
        if (getmsg.size() != 0) {
            baseQuickAdapter.addData(getmsg);
            if (getmsg.size() != 10) {
                baseQuickAdapter.loadComplete();
                addFootView(baseQuickAdapter);
            }
        } else {

        }
        baseQuickAdapter.notifyDataSetChanged();
        setLoadDataCompleted(true);

    }

    @Override
    public void showdialog() {
        showDialog();
    }

    @Override
    public void dissmissdialog() {
        dissMissDialog();
        mySrf.setRefreshing(false);
    }

    @Override
    public void Error(VolleyError error) {

        VolleyErrorHelper.getMessage(error);

    }
}
